import CryptoJS from "crypto-js";

// 参数配置
const SECRET_KEY = "63eeac68cf074c8c";

const crypto = {
  /**
   * 加密
   *
   * @param {*} value
   * @param {String} salt
   * @returns encryptString
   */
  encrypt: (value, salt) => {
    if (value === undefined || value === null || value === "") {
      throw new Error("加密内容不能为空");
    }

    const aseKey = CryptoJS.enc.Utf8.parse(salt || SECRET_KEY);
    const ivKey = CryptoJS.enc.Utf8.parse(salt || SECRET_KEY);

    const data = CryptoJS.enc.Utf8.parse(value);
    const encrypted = CryptoJS.AES.encrypt(data, aseKey, {
      iv: ivKey,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.ZeroPadding,
    });
    const ciphertext = CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
    return ciphertext.replace("==", "");
  },
  /**
   * 解密
   *
   * @param {String} value
   * @returns decryptObject
   */
  decrypt: (value, salt) => {
    if (value === undefined || value === null || value === "") {
      throw new Error("解密内容不能为空");
    }

    const aseKey = CryptoJS.enc.Utf8.parse(salt || SECRET_KEY);
    const ivKey = CryptoJS.enc.Utf8.parse(salt || SECRET_KEY);
    const Base64 = CryptoJS.enc.Base64.parse(value + "==");
    const data = CryptoJS.enc.Base64.stringify(Base64);

    const decrypted = CryptoJS.AES.decrypt(data, aseKey, {
      iv: ivKey,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.ZeroPadding,
    });

    return decrypted.toString(CryptoJS.enc.Utf8).toString();
  },
};

export default crypto;
